const { ObjectId } = require("mongodb");
const { hash, compare } = require("bcrypt");

module.exports = {
  async getCurrentUserProfile(ctx) {
    const currentUserId = new ObjectId(ctx.state.user.sub);

    const user = await ctx.mongoClient
      .db()
      .collection("users")
      .findOne({ _id: currentUserId });

    return user;
  },

  async updateCurrentUserInfo(ctx, params) {
    const currentUserId = new ObjectId(ctx.state.user.sub);
    const nickname = params.nickname;

    const userColl = ctx.mongoClient.db().collection("users");

    const user = await userColl.updateOne(
      {
        _id: currentUserId,
      },
      {
        $set: {
          nickname,
          updatedAt: new Date().getTime(),
        },
      }
    );
  },

  async updateCurrentUserPassword(ctx, params) {
    const currentUserId = new ObjectId(ctx.state.user.sub);
    const { oldPassword, newPassword } = params;

    const userColl = ctx.mongoClient.db().collection("users");

    const user = await userColl.findOne({ _id: currentUserId });

    const isPasswordValid = await compare(oldPassword, user.password);

    if (!isPasswordValid) {
      return ctx.throw({ code: 10302, message: "旧密码不正确" }); // throw new Error("旧密码不正确");
    }
    const newPasswordHash = await hash(newPassword, 10);

    await userColl.updateOne(
      {
        _id: currentUserId,
      },
      {
        $set: {
          password: newPasswordHash,
          updatedAt: new Date().getTime(),
        },
      }
    );
  },

  async updateCurrentUserAvatar(ctx, params) {
    const currentUserId = new ObjectId(ctx.state.user.sub);
    const avatar = params.avatar;

    const userColl = ctx.mongoClient.db().collection("users");

    await userColl.updateOne(
      {
        _id: currentUserId,
      },
      {
        $set: {
          avatar,
          updatedAt: new Date().getTime(),
        },
      }
    );
  },
};
